Skip to content

[7.0] Reduce invocation overhead for intercepted bean methods - #3545

Open
AngeloRubens wants to merge 17 commits into
weld:mainfrom
AngeloRubens:pr/proxy4-main
Open

AngeloRubens wants to merge 17 commits into
weld:mainfrom
AngeloRubens:pr/proxy4-main

Conversation

@AngeloRubens

@AngeloRubens AngeloRubens commented Oct 5, 2026 •

Copy link
Copy Markdown

Summary

Reduces the steady-state cost of calls to methods on intercepted beans. This PR includes the prerequisite client-proxy and interception-stack changes because they have not yet been merged upstream, followed by invocation-chain caching, smaller invocation contexts, shared empty arguments, per-thread stack reuse in InvocationContext.proceed(), and cached invokers. For eligible instance methods, a LambdaMetafactory function lets HotSpot inline interceptor dispatch. Reflection remains the fallback. A regression fix checks that a cached privileged handle cannot bypass a missing or revoked setAccessible override.

The Weld 6 backport is submitted separately against 6.0.

Validation

  • Full Weld CI on JDK 17/21 including unit tests, in-container tests, CDI TCK (WildFly and SE), relaxed mode, signature test and examples: Weld 7 run 37281293309.
  • Targeted access-override and cross-thread stack tests: 10 passed on each version, no failures or errors, run 37281149853.
  • The focused tests and all code were formatted by Weld's Maven formatter in CI before the full runs.

Performance

Interception scenarios derived from OWB benchmarks

The CDI benchmark scenarios are a Jakarta port of Mark Struberg's cdi-performance harness (fork). Results below are from the same GitHub Actions run, executed sequentially with one thread, two forks, 2 × 1 s warmup and 4 × 1 s measurement iterations. Values are JMH throughput in million benchmark operations per second (ops/µs); these are method calls in these scenarios, not HTTP requests.

Scenario Weld 7 base OWB 4.1.1 Weld 7 + PR #3545 PR vs Weld base PR vs OWB
Method intercepted 8.7 M/s 15.3 M/s 48.3 M/s 5.54× (+454%) 3.16× (+216%)
Class intercepted 8.8 M/s 16.0 M/s 50.5 M/s 5.73× (+473%) 3.16× (+216%)

In these two interception scenarios, the PR moves Weld from below OWB to above it. This does not describe every benchmark in the suite: for example, OWB remains faster in the application-scoped and request-scoped scenarios. The quick comparison has only two forks and relatively short iterations, so the exact ratios need confirmation with longer repeated runs. Full report and raw JMH results, run 37314014340.

Official Weld JMH suite

As an independent cross-check, Weld's official microbenchmark suite was run against base and PR sequentially on the same runner, with four threads, five forks, and 5 × 5 warmup/measurement iterations. It exercises its own Decorator and Interceptor workloads, which are distinct from the interception scenarios above.

Benchmark Weld 7 base Weld 7 + PR #3545 Change
Decorator 294.30 ops/s 303.76 ops/s +3.21%
Interceptor 352.94 ops/s 350.82 ops/s −0.60%

The official-suite differences are small relative to their JMH error margins and do not establish a general throughput reversal. Official JMH run 37335225598.

In the separate proxy-3-to-proxy-4 incremental comparison, Boot/shutdown was 45.47 ± 3.30 → 46.19 ± 2.67 ms on Weld 7 and 44.95 ± 3.15 → 48.15 ± 2.76 ms on Weld 6. A separate ten-fork cold-start run invokes intercepted methods on a fresh container: Weld 7 was 685.93 ± 25.66 ms plain and 688.85 ± 15.61 ms with first intercepted calls; Weld 6 was 686.08 ± 22.97 and 691.57 ± 16.62 ms. These runs show no clear startup regression. Cold-start results, run 37281596417.

The GC profile measured 0.0008 ± 0.0221 B/op for the intercepted-method benchmark, down from about 64 B/op in the previous proxy-3 profile. This depends on JIT inlining/escape analysis and is not guaranteed for polymorphic or otherwise different call sites. Profile, run 37281324917.

No CDI self-invocation semantics are intentionally changed. The earlier client-proxy and stack changes are included for review because this optimization series depends on them.

Origin of the work

This work originated in the analysis of OpenWebBeans (OWB). Its approach to invocation and interception performance was the starting point for this optimization series, which was adapted to Weld internals and compatibility requirements.

@AngeloRubens
AngeloRubens requested a review from manovotn as a code owner October 5, 2026 12:41
…s when none exists

Every business method invocation on a client proxy calls
InterceptionDecorationContext.startIfNotEmpty(). When the caller is not
intercepted and no RequestScopedCache is active (e.g. Weld SE, or any
invocation outside of an HTTP/EJB request), getStack() allocated a new
Stack (+ ArrayDeque), set it into the thread-local and then immediately
removed it again in removeIfEmpty(). The net effect is nothing, but
ThreadLocal.set()/remove() plus the allocation dominate the cost of a
client proxy invocation.

Return null straight away if there is no stack on the current thread.
This is semantically identical: an absent stack is an empty stack and
the old code never left anything behind in that case (with an active
RequestScopedCache the empty stack would have been cached; it is now
created lazily by the first startIfNotOnTop()/getStack() instead).
… stack

Outside of an active RequestScopedCache each intercepted invocation (and
each non-intercepted method of an intercepted subclass) creates a Stack,
sets it into the thread-local and removes it again once the stack gets
empty. ThreadLocal.remove() clears the weak reference of the map entry
(native Reference.clear0) and expunges the entry, so the next set()
allocates a new WeakReference entry again. The profile of an intercepted
@ApplicationScoped bean shows remove() + expunge + entry allocation as
the most expensive part of the invocation.

Set the thread-local value to null instead: the entry is reused, and a
null value does not retain any Weld class, so there is no class loader
leak. Also allocate the ArrayDeque with a small initial capacity as the
stack is usually very shallow.
ContextBeanInstance.getInstance() called Container.isSet(contextId) on
each invocation to detect usage of a client proxy after shutdown. This is
a ConcurrentHashMap lookup in RegistrySingletonProvider and shows up in
the profile of @ApplicationScoped invocations.

ContextBeanInstance now keeps the Container it was created for. Container
gets a volatile cleanedUp flag set at the beginning of cleanup(); while
it is false the container is guaranteed to be registered, so the
registry lookup is only performed after the container was cleaned up.
Behaviour is unchanged (including the case where a new container was
registered under the same id afterwards).
Every invocation of an intercepted subclass method (both intercepted and
non-intercepted methods push the subclass handler) outside of a request
allocated a new Stack and ArrayDeque, set the thread-local and cleared it
again once the stack became empty. Within a request the stack was kept in
the RequestScopedCache instead.

The thread-local now holds a small Object[] holder (a JDK class) that
references the per-thread stack strongly only while it is not empty and
weakly otherwise. An idle thread never retains a Weld class, so there is
no class loader leak, and the stack is reused until the next GC clears
the weak reference. The RequestScopedCache registration and the validity
tracking of the stack are no longer needed.
…rst used

Client proxies call InterceptionDecorationContext.startIfNotEmpty() on every
invocation, i.e. a ThreadLocal lookup. As long as no thread has ever created
an interception context (no intercepted or decorated method has been
invoked yet, which is always the case in deployments without interceptors
and decorators) the lookup cannot find anything.

startIfNotEmpty() now invokes a constant MethodHandle guarded by a
SwitchPoint: it returns null without any lookup until the first per-thread
stack holder is created, when the SwitchPoint is invalidated (once, before
the holder is published to that thread). The JIT compiles the guard to
nothing, so applications that do use interception do not pay for an
additional check either. A thread can only have an active stack if it
created its holder itself, so the switch cannot be observed too late.
… check in client proxies

ContextBeanInstance keeps the bean as RIBean when possible so that the
client proxy invocation goes straight to the bean's ContextualInstanceStrategy
(for @ApplicationScoped beans a volatile read of the cached instance)
instead of going through the instanceof check in ContextualInstance.
Invalidation is unchanged: the strategy remains the single place where the
instance is cached.
Replace the ArrayDeque inside InterceptionDecorationContext.Stack with an
array and a size index that grows on demand. push/pop/peek/startIfNotOnTop
need fewer branches and no ring-buffer index arithmetic. Popped slots are
cleared so that no handler is retained, and the weakly referenced idle stack
(no class loader leak) is unchanged. Null elements are still rejected and
popping an empty Stack still throws NoSuchElementException.
Interceptor methods (@AroundInvoke etc.) and the proceed method of an
around invoke chain (WeldSubclass.method$$super() or the decorated method)
used to be invoked by Method.invoke(). They are now invoked through a
MethodHandle adapted to (Object, Object)Object or (Object, Object[])Object,
created lazily upon the first invocation and cached per method
(MethodInvoker; per interceptor metadata for interceptor methods, per
declaring class via a ClassValue for proceed methods).

The semantics of Method.invoke() are kept exactly:
- the handle is only used if the receiver is an instance of the declaring
  class and every argument matches the parameter type exactly (reference
  type or exact wrapper of the primitive type), i.e. if the invocation
  cannot fail before reaching the method; otherwise (null receiver, wrong
  arguments, widening primitive conversions, static methods...) the
  Method is invoked reflectively and throws the same exceptions as before
- any Throwable thrown by the invoked method is wrapped in an
  InvocationTargetException, so that the existing unwrapping code paths
  are unchanged
- accessibility is never changed; a handle that cannot be created (e.g.
  module readability) results in reflective invocations
…hed interception chains

InterceptorMethodHandler.invoke() called Reflections.ensureAccessible()
(AccessibleObject.canAccess()) and TargetClassInterceptorMetadata
.isInterceptorMethod() (a hash set lookup) upon every invocation, before
looking up the cached interception chain. A cached chain implies that both
checks have been performed already for the given method and proceed method
(the chain is created after them), and neither result can change, so the
chain is now looked up first and used directly.
… instance

Avoids the ConcurrentHashMap lookup in InterceptorMethodHandler for the
first intercepted method that has been invoked on a given instance (e.g. a
bean with a single intercepted method). The field is set at most once, the
chain is immutable (final fields only), other methods keep using the map.
…ocation contexts

The timer field of AbstractInvocationContext was always null and the
constructor field is only needed for around construct interception
(SimpleInvocationContext). Moving the latter to SimpleInvocationContext
reduces the size of the InvocationContext allocated upon every intercepted
invocation by 8 bytes (compressed oops), which compensates for the method
handle invoker field. No behavior change: getTimer() returned null before
as well, getConstructor() and the parameter checks are unchanged.
…out parameters

The intercepted subclass passes a shared, immutable empty array to the
method handler for methods without parameters instead of allocating a new
one upon every invocation (InvocationContext.getParameters() returns an
empty array as before; setParameters() replaces the array, it never writes
into it).
…nvoking thread

An around invoke InvocationContext now keeps the interception stack of the
thread that created it. proceed() uses it directly if it is called on the
same thread (Thread.currentThread() comparison) instead of looking up the
stack in the thread-local again. While the context references the stack,
it is guaranteed to be the stack getStack() returns on that thread (see
InterceptionDecorationContext.getStack()), so the behavior is the same.
On another thread (e.g. asynchronous proceed), the thread-local lookup is
performed as before.

The additional field does not increase the size of the context (it fits
into the padding left by the removal of the timer/constructor fields).
For methods with a non-void return type and no parameter or a single
reference type parameter (e.g. @AroundInvoke interceptor methods and
WeldSubclass.getter$$super()), MethodInvoker creates a Function/BiFunction
via LambdaMetafactory (in the package of the declaring class, requires the
package to be open to Weld) so that the JIT can inline the invocation,
which is not possible with a method handle stored in a field. Same
argument checks and exception wrapping as for the method handle; if the
lambda cannot be created, the method handle (or reflection) is used.
@AngeloRubens AngeloRubens changed the title Reduce invocation overhead for intercepted bean methods [7.0] Reduce invocation overhead for intercepted bean methods Oct 5, 2026
@manovotn

manovotn commented Oct 5, 2026

Copy link
Copy Markdown
Member

Hello @AngeloRubens and thank you for the PR.

I am not sure I will have the time and capacity and review this in the very near future but it is definitely on my TODO list so please bear with me.

In the meantime, did you know that Weld had its own micro benchmarks using JMH? Take a look at https://github.com/weld/weld-core-benchmarks
It's been a while since I last used it but it looks like a perfect candidate for your case. There were interceptor (and therefore probably also decorator) tests in there. We should probably take a look at measuring the diff there.

@lprimak

lprimak commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@manovotn Would be great if you are able to tackle this one. This would make Weld substantially perform as good as Arc.

Thank you Angelo for this

@manovotn

manovotn commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

@manovotn Would be great if you are able to tackle this one. This would make Weld substantially perform as good as Arc.

Thank you Angelo for this

I am aware of this PR but was preoccupied elsewhere and I now also have some PTO planned which will unfortunately delay this further.
If you wish to truly dig into it and help with review, be my guest :-)

Below are my uncensored thoughts, do not take that as a criticism. That is just my honest though process about this PR.

I am not against this PR as such, however...

  • It is apparently fully AI generated, so while the intention might be good, the result might not
  • The measurements presented here are not convincing
    • It is showing an original OWB measurement with huge increase which seems nice but I don't know enough about that measurement to say if it is truly relevant. It can easily be tailored to favour OWB heavily by picking the right scenarios; I mean the README there literally boasts by showing that which is a red flag to me. So is the fact that the repo is 9y old. Yes, I did not check the updated fork. It might well be okay, I am just saying what I'd be checking.
    • It is also using the Weld micro benchmark that we have and in that case, it shows basically no improvement - that's another 'thread carefully' flag. Those tests were, in the past, pretty good in showing how Weld behaves if you change anything around interceptors.
    • This PR needs to be thoroughly checked to see what it optimizes for and we should definitely re-check the micro benchmark we have and see if it meets the requirements and isn't an edge case itself
  • The description states No CDI self-invocation semantics are intentionally changed which is something we need to verify. Weld had different self-invocation policy that OWB (IIRC) and while that behavior isn't mandated by the spec, we probably don't want to break existing apps that might depend on it (intentionally or otherwise).

To be clear, overall, I view this PR as definitely worth exploring.
I am just aware of the fact that this task won't be trivial and I have been stretched thin across other duties and projects lately.

@lprimak

lprimak commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Thanks for your feedback, I am sure Angelo can answer any questions, and I can help if needed!

@AngeloRubens

AngeloRubens commented Nov 4, 2026 •

Copy link
Copy Markdown
Author

Thanks for the detailed feedback, and no rush. Enjoy the PTO. I tried to answer the three concrete points with data instead of arguments. Everything ran on GitHub Actions (JDK 21, 4-core shared runners), nothing is tuned by hand. I replaced the numbers of my first version of this comment with a longer run (5 forks) that also benchmarks main without this PR as the baseline.

1. weld-core-benchmarks

I forked weld-core-benchmarks and ran it against main without this PR (12251dc, the base of the PR), 7.0.0.Final and the head of this PR (38f94f3). The only change to the suite is one line in BaseBenchmark (WeldContainer.instance() no longer compiles on Weld 7, so the unbound RequestContext is selected from the container directly). Options: -f 5 -wi 3 -w 3s -i 5 -r 3s (shorter warmup and iterations than the suite defaults), two rounds with the variants interleaved, so a slow runner does not favour one side. Throughput change of this PR relative to main without it (main and 7.0.0.Final are within 2% of each other):

benchmark 1 thread all threads (4)
InterceptorBenchmark +301% +278% (error about 13%)
NotInterceptedMethodBenchmark +475% about +460-530% (the baseline has an 18% error)
DecoratorBenchmark +51% +73%
ComplexBenchmark +14%
ApplicationScopedBenchmark +2% (noise) +1% (noise)
DependentBenchmark, BaselineBenchmark 0% (noise)

So I do see a difference on the interceptor and decorator benchmarks, but not on plain scope lookups, which is what I would expect from a patch that only touches the invocation path. I cannot tell why you saw no improvement. If you can tell me which benchmark and options you used I will run exactly that. The workflow is in the fork (ci/bench branch of AngeloRubens/weld-core-benchmarks) if you want to rerun it. The 6.0 backport shows the same numbers (e.g. +310% interceptor, +510% non-intercepted, +84% decorator at 1 thread).

Caveats: shared 4-core runners; the single-thread column is the one I would trust (errors under 5% for the interceptor, non-intercepted and decorator rows); the multi-thread rows only give an order of magnitude. I have not checked whether the benchmark is itself an edge case, as you suggest. The @Dependent beans in it take the subclass path without a client proxy, so they do not cover @ApplicationScoped interceptors at all.

Request scope, and what is in this PR and what is not

This PR does not contain the request cache. That is #3552, stacked on this one. To keep the two contributions apart I ran the request scoped benchmarks of the same suite (5 forks, 1 round, 1 thread, ci/reqscope branch of the fork):

benchmark this PR (#3545) vs main #3552 on top of #3545 both vs main
RequestScopedClientProxyBenchmark +140% +678% +1769%
ComplexBenchmark +17% +14% +34%
SimpleRequestScopedObserverBenchmark +5% +19% +25%
EventMetadataRequestScopedObserverBenchmark +11% +14% +27%
ApplicationScopedBenchmark 0% +37% +36% (I have not investigated why this one moves)

With all threads the proxy benchmark shows +326% for #3545 and about +2600% with #3552, but the baseline has a 25% error there, so only the single-thread values are solid.

The request cache only matters in the unbound request context (RequestContextController, @ActivateRequestContext, Weld SE). In a servlet container the request context already had the cache. So the +1769% is the extreme of a micro benchmark that calls only a request scoped proxy.

2. The OWB comparison

Fair point. The cdi-performance numbers are one view and I would not rely on them alone. I am happy to drop them from the description if you prefer and keep only the Weld suite.

3. Self-invocation

You are right that "no semantics intentionally changed" was an unverified claim. I wrote a small probe (probe/SelfInvocationProbe.java in the same fork) that prints the observable behaviour of 31 scenarios and diffs the output between builds: self-invocation from unintercepted and intercepted methods (public, protected, package-private, this.a()), class-level bindings, @ApplicationScoped and @RequestScoped beans, @PostConstruct calling an intercepted method, decorators with self-invocation, checked and runtime exceptions through the chain, parameter changes and context data between interceptors, proceed() twice, re-entrancy (ping/pong between two beans) and 8 threads x 20000 calls. On Weld 7, 7.0.0.Final and this PR print identical output in three separate JVM runs each.

It is not exhaustive. It covers what I thought of, not everything an application might depend on.

On the 6.0 backport (#3546) it found one reproducible difference that is not on main: the order of the binding annotations in InvocationContext.getContextData() under org.jboss.weld.interceptor.bindings is [Trace2, Trace] instead of [Trace, Trace2] for a method with two bindings. It is deterministic. I have not looked into the cause yet and will do that before anything else on that PR.

4. AI

You are right: the change was written with AI assistance (Claude). That is why I tried to back the claims with measurements and a behaviour diff that anyone can rerun, instead of asking you to take them on trust.

@AngeloRubens

AngeloRubens commented Nov 5, 2026 •

Copy link
Copy Markdown
Author

Follow-up on the measurement concern. No rush, whenever you are back.

I tried one more change on top of #3552 for BeanManager.getBeans(Class) without qualifiers (callers such as RESTEasy do this per request): reuse the already resolved result per class instead of building a Resolvable each time. I opened it on my fork only, for discussion, not against weld/core: AngeloRubens#1

Micro benchmark of one getBeans() call (JMH, 5 forks x 2 interleaved rounds, GitHub Actions JDK 21 4-core shared runners, baseline = #3552 head):

benchmark baseline with the change change
getBeans(Class), 1 thread 136.8 ns 3.5 ns -97%
getBeans(Class), 8 classes in turn, 1 thread 147.3 ns 4.0 ns -97%
getBeans(Class), 4 threads 255.0 ns 7.2 ns -97%
allocation per call 640 B ~0 B -100%
control: getBeans(Class, @Default) 318.1 ns 319.7 ns +0.5% (noise)
control: getBeans(Class, @Special) 375.2 ns 371.9 ns -0.9% (noise)

The controls take the old path in both builds and do not move. This is the cost of the call itself on a cache hit, not an application-level gain. Limits: shared runners, and I did not run the older weld-core-benchmarks suite for this change. Only one of the 6 new tests fails without the change, the other five pin the old behaviour. Full test suite and TCK (SE) pass on the fork. The PR text has the details, including that it was written with AI assistance and reviewed in two adversarial passes (the first found a real race with clear(), fixed by replacing the map). Benchmark source: branch ci/getbeans-micro of https://github.com/AngeloRubens/weld-core-benchmarks

I still owe you an answer on the 6.0 binding-order difference for #3545. Nothing in the change above touches interceptors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants